package com.tiktok.controller;

import com.tiktok.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class FileUploadController {

    // 视频存储路径
    private static final String VIDEO_PATH = "D:\\api_homework\\tiktok_videos";
    // 图片存储路径  
    private static final String IMAGE_PATH = "D:\\api_homework\\tiktok_images";
    // 用户头像存储路径
    private static final String AVATAR_PATH = "D:\\api_homework\\tiktok_user_photo";

    /**
     * 上传视频文件
     */
    @PostMapping("/video")
    public Result<Map<String, Object>> uploadVideo(@RequestParam("file") MultipartFile file) {
        
        if (file.isEmpty()) {
            return Result.badRequest("文件不能为空");
        }

        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return Result.badRequest("文件名不能为空");
        }

        String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!isValidVideoExtension(extension)) {
            return Result.badRequest("不支持的视频格式，支持格式：mp4, avi, mov, wmv, flv, webm");
        }

        // 检查文件大小 (100MB)
        if (file.getSize() > 100 * 1024 * 1024) {
            return Result.badRequest("视频文件大小不能超过100MB");
        }

        try {
            // 创建目录
            createDirectoryIfNotExists(VIDEO_PATH);

            // 生成新文件名
            String newFilename = generateFileName(extension);
            
            // 按日期创建子目录
            String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String fullPath = VIDEO_PATH + File.separator + dateDir;
            createDirectoryIfNotExists(fullPath);

            // 保存文件
            Path filePath = Paths.get(fullPath, newFilename);
            Files.copy(file.getInputStream(), filePath);

            // 构造返回的URL
            String videoUrl = "/api/files/video/" + dateDir.replace("\\", "/") + "/" + newFilename;

            Map<String, Object> result = new HashMap<>();
            result.put("videoUrl", videoUrl);
            result.put("originalName", originalFilename);
            result.put("fileName", newFilename);
            result.put("fileSize", file.getSize());

            return Result.success("视频上传成功", result);

        } catch (IOException e) {
            log.error("视频上传失败", e);
            return Result.error("视频上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传封面图片
     */
    @PostMapping("/image")
    public Result<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        
        if (file.isEmpty()) {
            return Result.badRequest("文件不能为空");
        }

        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return Result.badRequest("文件名不能为空");
        }

        String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!isValidImageExtension(extension)) {
            return Result.badRequest("不支持的图片格式，支持格式：jpg, jpeg, png, gif, bmp, webp");
        }

        // 检查文件大小 (10MB)
        if (file.getSize() > 10 * 1024 * 1024) {
            return Result.badRequest("图片文件大小不能超过10MB");
        }

        try {
            // 创建目录
            createDirectoryIfNotExists(IMAGE_PATH);

            // 生成新文件名
            String newFilename = generateFileName(extension);
            
            // 按日期创建子目录
            String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String fullPath = IMAGE_PATH + File.separator + dateDir;
            createDirectoryIfNotExists(fullPath);

            // 保存文件
            Path filePath = Paths.get(fullPath, newFilename);
            Files.copy(file.getInputStream(), filePath);

            // 构造返回的URL
            String imageUrl = "/api/files/image/" + dateDir.replace("\\", "/") + "/" + newFilename;

            Map<String, Object> result = new HashMap<>();
            result.put("imageUrl", imageUrl);
            result.put("originalName", originalFilename);
            result.put("fileName", newFilename);
            result.put("fileSize", file.getSize());

            return Result.success("图片上传成功", result);

        } catch (IOException e) {
            log.error("图片上传失败", e);
            return Result.error("图片上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/avatar")
    public Result<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        
        if (file.isEmpty()) {
            return Result.badRequest("文件不能为空");
        }

        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return Result.badRequest("文件名不能为空");
        }

        String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!isValidImageExtension(extension)) {
            return Result.badRequest("不支持的头像格式，支持格式：jpg, jpeg, png, gif, bmp, webp");
        }

        // 检查文件大小 (5MB)
        if (file.getSize() > 5 * 1024 * 1024) {
            return Result.badRequest("头像文件大小不能超过5MB");
        }

        try {
            // 创建目录
            createDirectoryIfNotExists(AVATAR_PATH);

            // 生成新文件名
            String newFilename = generateFileName(extension);
            
            // 按日期创建子目录
            String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String fullPath = AVATAR_PATH + File.separator + dateDir;
            createDirectoryIfNotExists(fullPath);

            // 保存文件
            Path filePath = Paths.get(fullPath, newFilename);
            Files.copy(file.getInputStream(), filePath);

            // 构造返回的URL
            String avatarUrl = "/api/files/avatar/" + dateDir.replace("\\", "/") + "/" + newFilename;

            Map<String, Object> result = new HashMap<>();
            result.put("avatarUrl", avatarUrl);
            result.put("originalName", originalFilename);
            result.put("fileName", newFilename);
            result.put("fileSize", file.getSize());

            return Result.success("头像上传成功", result);

        } catch (IOException e) {
            log.error("头像上传失败", e);
            return Result.error("头像上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量上传文件（视频+封面）
     */
    @PostMapping("/batch")
    public Result<Map<String, Object>> batchUpload(
            @RequestParam("video") MultipartFile videoFile,
            @RequestParam(value = "cover", required = false) MultipartFile coverFile) {
        
        Map<String, Object> result = new HashMap<>();
        
        // 上传视频
        Result<Map<String, Object>> videoResult = uploadVideo(videoFile);
        if (videoResult.getCode() != 200) {
            return videoResult;
        }
        result.putAll(videoResult.getData());

        // 上传封面（如果有）
        if (coverFile != null && !coverFile.isEmpty()) {
            Result<Map<String, Object>> imageResult = uploadImage(coverFile);
            if (imageResult.getCode() != 200) {
                return imageResult;
            }
            result.putAll(imageResult.getData());
        }

        return Result.success("文件上传成功", result);
    }

    /**
     * 检查视频文件扩展名
     */
    private boolean isValidVideoExtension(String extension) {
        return extension.matches("\\.(mp4|avi|mov|wmv|flv|webm)$");
    }

    /**
     * 检查图片文件扩展名
     */
    private boolean isValidImageExtension(String extension) {
        return extension.matches("\\.(jpg|jpeg|png|gif|bmp|webp)$");
    }

    /**
     * 生成唯一文件名
     */
    private String generateFileName(String extension) {
        return UUID.randomUUID().toString().replace("-", "") + extension;
    }

    /**
     * 创建目录（如果不存在）
     */
    private void createDirectoryIfNotExists(String path) throws IOException {
        File directory = new File(path);
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                throw new IOException("无法创建目录：" + path);
            }
        }
    }
} 